package cn.wanghaomiao.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

/**
 * HBase工具类
 * @author 胡宇鹏
 *
 */
public class HBaseUtil {
	static String  hbase_master ;
	static String  hbase_zookeeper_quorum;
	static String  hbase_zookeeper_property_clientPort;
	static String  hbase_root_dir;
	
	static Configuration configuration;
    static Connection connection;  
    static Admin admin;  
	
	static{
        Properties prop = new Properties();
        try {
            InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("Configure.properties");
            prop.load(in);
            in.close();
        } catch (Exception e) {
        	e.printStackTrace();
        }
        hbase_master = prop.getProperty("hbase_master");
        hbase_zookeeper_quorum = prop.getProperty("hbase_zookeeper_quorum");
        hbase_zookeeper_property_clientPort = prop.getProperty("hbase_zookeeper_property_clientPort");
        hbase_root_dir = prop.getProperty("hbase_root_dir");
	}  
	
	/**
	 * 获取操作hbase的对象
	 * @return
	 */
    public static Admin getAdmin(){
        configuration = HBaseConfiguration.create();  
        configuration.set("hbase.zookeeper.property.clientPort",hbase_zookeeper_property_clientPort);  
        configuration.set("hbase.zookeeper.quorum",hbase_zookeeper_quorum);  
        configuration.set("hbase.master", hbase_master);  
        configuration.set("hbase.root.dir", hbase_root_dir); 
        try {  
            connection = ConnectionFactory.createConnection(configuration);  
            admin = connection.getAdmin();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return admin;
    }
    
    /**
     * 获取连接
     * @return
     */
    public static Connection getConn(){
        configuration = HBaseConfiguration.create();  
        configuration.set("hbase.zookeeper.property.clientPort",hbase_zookeeper_property_clientPort);  
        configuration.set("hbase.zookeeper.quorum",hbase_zookeeper_quorum);  
        configuration.set("hbase.master", hbase_master);  
        configuration.set("hbase.root.dir", hbase_root_dir); 
        try {  
            connection = ConnectionFactory.createConnection(configuration);    
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        return connection;   	
    }
	
    /** 
     * 关闭连接 
     */  
    public static void close() {  
        try {  
            if (null != admin) {  
                admin.close();  
            }  
            if (null != connection) {  
                connection.close();  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    } 
}
